package com.money.tracker.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p>
 * 线程池配置
 * <p>
 *
 * @author zhangshuai
 * @date 2024/09/21
 */
@Configuration
@Slf4j
public class ThreadPoolConfig {

    @Bean
    public Executor asyncServiceExecutor() {
        log.info("Start asyncServiceExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 根据实际需求和系统资源进行调整
        // 核心线程数为 CPU 核心数
        int corePoolSize = Runtime.getRuntime().availableProcessors();
        log.info("异步线程池-corePoolSize:"+corePoolSize);
        executor.setCorePoolSize(corePoolSize);
        // 最大线程数为核心线程数的两倍
        executor.setMaxPoolSize(corePoolSize * 2);
        // 根据实际需求进行调整
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("money-async-service-");
        // 使用AbortPolicy拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();
        return executor;
    }
}